package com.edu.chapter06;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class AIDLActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MyService-3";
    private boolean isBound = false; // 绑定状态标志

    public IMyAidlInterface anInterface;
    ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected");
            if (!isBound)
                anInterface = IMyAidlInterface.Stub.asInterface(service);
            isBound = true;
            try {
                Log.d(TAG, "res:" + anInterface.minus(10, 20));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            /*
             * 作用定位
             * onServiceDisconnected() 是异常断连的监听器，用于处理服务意外终止后的逻辑（如重连、状态重置）。
             * 正常解绑需在 onStop() 或 onDestroy() 中主动调用 unbindService()
             */
            Log.d(TAG, "onServiceDisconnected");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aidlactivity);
        findViewById(R.id.btn_calculate).setOnClickListener(this);
        findViewById(R.id.btn_stop).setOnClickListener(this);

        Intent intent = new Intent(this, MyService2.class);
        // 标志位：若 Service 未运行则自动创建
        Log.d(TAG, "After Intent intent = new Intent(this, MyService2.class);");
        if (!isBound) {
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_calculate) {
            try {
                Toast.makeText(AIDLActivity.this, "Result: " + anInterface.add(1, 2), Toast.LENGTH_SHORT).show();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else if (v.getId() == R.id.btn_stop) {
            if (isBound) {
                unbindService(connection);
                isBound = false;
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBound) {
            unbindService(connection);
            isBound = false;
        }
    }
}